package com.itcast.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.itcast.health.pojo.Permission;
import com.itcast.health.pojo.Role;
import com.itcast.health.pojo.User;
import com.itcast.service.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> authorities = new ArrayList<>();
        User user = userService.findByUser(username);
        if (user != null) {
            Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                Set<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
        } else {
            return null;
        }
        UserDetails userDetails=new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
        return userDetails;
    }
}
